package com.xgimi.locales.ui

import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.ui.DialogWrapper
import com.xgimi.locales.bean.ExportConfig
import com.xgimi.locales.bean.RowBean
import com.xgimi.locales.ext.createCheckBoxListView
import com.xgimi.locales.ext.labelSize
import com.xgimi.locales.ext.showError
import com.xgimi.locales.ext.showMessage
import com.xgimi.locales.utils.Constant
import com.xgimi.locales.utils.ExcelUtil
import com.xgimi.locales.utils.XmlParserUtil
import java.awt.Dimension
import java.io.File
import java.util.Collections
import javax.swing.*


/**
 * 导出界面
 */
class ExportConfigDialog(val anActionEvent: AnActionEvent, private val exportConfig: ExportConfig) : DialogWrapper(true) {

    companion object {
        fun show(anActionEvent: AnActionEvent, exportConfig: ExportConfig) {
            ExportConfigDialog(anActionEvent, exportConfig).apply {
                pack()
                showAndGet()
            }
        }
    }

    init {
        init()
        title = "xml导出excel 参数配置"
        setSize(500, 100)
    }

    private var rootBox: Box? = null

    override fun createCenterPanel(): JComponent =
        Box.createVerticalBox().apply {
            rootBox = this
            rootBox?.refreshViews()
        }

    private fun Box.refreshViews() {
        removeAll()
        // 目录选择
        add(createFilePathBox())
        add(Box.createVerticalStrut(10))
        // 模块列表
        add(createModulesBox(exportConfig.allModuleBeans?.map { it.moduleName } ?: mutableListOf()))
        add(Box.createVerticalStrut(10))
        val langs = HashSet<String>()
        exportConfig.allModuleBeans?.forEach {
            it.xmlFiles.forEach {
                langs.add(it.langName)
            }
        }
        exportConfig.allLangs = langs.toList()
        Collections.sort(exportConfig.allLangs)

        // 语言列表
        val listAllLangs = exportConfig.allLangs!!.map { "$it    ${Constant.langMap[it]}" }
        add(createLangsBox(listAllLangs))
//        add(Box.createVerticalStrut(10))
//        add(createOnlineTransBox())
//        add(Box.createVerticalStrut(10))
//        add(createOnlineLangTempType())
    }

    private var excelPath: JTextField? = null
    // 选择文件
    private fun createFilePathBox(): JComponent =
        Box.createHorizontalBox().apply {
            add(JLabel("Excel文件路径:").labelSize())
            add(Box.createHorizontalGlue())
            add(Box.createHorizontalBox().apply {
                excelPath = JTextField()
                excelPath?.isEnabled = false
                add(excelPath.apply { minimumSize = Dimension(300, 10) })
                add(Box.createHorizontalStrut(10))
                add(JButton("选择文件").apply {
                    addActionListener {
                        //选择文件
                        val fileChooser = JFileChooser()
                        fileChooser.fileSelectionMode = JFileChooser.FILES_AND_DIRECTORIES
                        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
                            val selectedFile: File = fileChooser.selectedFile
                            if (selectedFile.exists()) {
                                excelPath!!.text = selectedFile.absolutePath
                            }
                        }
                    }
                })
            })
        }

    private var moduleJCheckBoxList: List<JCheckBox>? = null
    // 所有模块列表选型
    private fun createModulesBox(modules: List<String>): JComponent =
        Box.createHorizontalBox().also { parent ->
            parent.add(JLabel("选择模块:").labelSize())
            parent.add(Box.createHorizontalGlue())
            moduleJCheckBoxList = mutableListOf()
            val moduleListView = createCheckBoxListView(modules) { cb, text ->
                cb.isSelected = true
                moduleJCheckBoxList = moduleJCheckBoxList?.plus(cb)
            }
            parent.add(moduleListView)
        }

    private var langsJCheckBoxList: List<JCheckBox>? = null
    //所有语言类型
    private fun createLangsBox(langs: List<String>): JComponent =
        Box.createHorizontalBox().also { parent ->
            parent.add(JLabel("选择语言类型:").labelSize())
            parent.add(Box.createHorizontalGlue())
            langsJCheckBoxList = mutableListOf()
            val moduleListView = createCheckBoxListView(langs) { cb, text ->
                //如果excel中的module在项目中找不到则不可选择
                cb.isSelected = true
                langsJCheckBoxList = langsJCheckBoxList?.plus(cb)
            }
            parent.add(moduleListView)
        }

    override fun doOKAction() {
        val excel = excelPath?.text ?: ""
        val file = File(excel)
        if (!file.exists()) {
            "Excel文件地址不存在！".showError()
            return
        }
        // 模块选中
        val moduleNames = moduleJCheckBoxList!!.filter { it.isSelected }.map { it.text }
        println("doOKAction moduleNames:${moduleNames} exportConfig.allModuleBeans:${exportConfig.allModuleBeans}")
        if (moduleNames.isEmpty()) {
            "请至少选择一个module！".showError()
            return
        }
        exportConfig.excelPath = excel
        if (file.isDirectory) {
            exportConfig.excelPath = File(file, "${exportConfig.projectName}$moduleNames.xlsx").absolutePath
        }

        // 语言选中
//        val langNames = langsJCheckBoxList!!.filter { it.isSelected }.map { it.text }
        // 获取用户选择的语言类型
        exportConfig.selectLangs = langsJCheckBoxList?.filter {
            val index = langsJCheckBoxList?.indexOf(it) ?: -1
            it.isSelected && index >= 0 }?.map {
            val index = langsJCheckBoxList?.indexOf(it) ?: -1
            exportConfig.allLangs?.get(index)!!
        }

        if (exportConfig.selectLangs?.isEmpty() == true) {
            "请至少选择一个语言类型！".showError()
            return
        }

//        super.doOKAction()
        //更新配置缓存
        exportConfig.selectModuleBeans = exportConfig.allModuleBeans?.filter { moduleNames.contains(it.moduleName) }
        println("doOKAction exportConfig.selectModuleBeans size:${exportConfig.selectModuleBeans?.size}")
        if (exportConfig.selectModuleBeans.isNullOrEmpty()) {
            "老铁，请选择模块先".showError()
            return
        }
        runTask()
    }

    private fun runTask() {
        println("runTask")
        val startTime = System.currentTimeMillis()
        XmlParserUtil.parseXmlByModule(exportConfig) {
//            println("parseXmlByModule rowBean:$it")
        }.also {
            val list = ArrayList<RowBean>()
            it.forEach {
                list.addAll(it.value)
            }
            ExcelUtil.writeDataBySheetName(exportConfig, list)
        }
        val endTime = System.currentTimeMillis()
        "导出数据完成,耗时：${(endTime - startTime) / 1000}s".showMessage()
    }

}